<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="40%">
    <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        size="30"
        :destroy-on-close="true"
    >
      <el-form-item label="用户名">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="旧的密码" prop="password">
        <el-input v-model="ruleForm.password" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新的密码" prop="configPassword">
        <el-input v-model="ruleForm.configPassword" type="password"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, reactive} from 'vue'
import {useAdminStore} from '@/stores/modules/user/index.js'


const store = useAdminStore()
const emit = defineEmits(['submit'])
const dialogVisible = ref(false)
// 获取表单dom元素
const ruleFormRef = ref()
// 表单数据绑定
const ruleForm = reactive({
  name: store.admin_username,
  password: store.admin_password,
  configPassword: '',
})
const rules = reactive({
  configPassword: [
    {
      required: true,
      message: '请输入新的密码',
      trigger: 'blur',
    },
    {pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符', trigger: 'blur'},
    {
      validator:(rule, value, callback) => {
        console.log(ruleForm.password)
        if (value === ruleForm.password) {
          callback('两次输入的密码必须不相同')
        }
        callback() // 验证通过时调用回调函数，表示验证通过。
      }
    }
  ],
})
// 表单提交
const submitForm =(formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      emit('submit', ruleForm.configPassword)
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
  }
const show = () => {
  dialogVisible.value = true
}
defineExpose({
  show,
})
</script>

<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>